import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { WinstonModule, WinstonModuleOptions, utilities } from 'nest-winston';
import * as winston from 'winston';
import { Console } from 'winston/lib/winston/transports';
import 'winston-daily-rotate-file';
import DailyRotateFile = require('winston-daily-rotate-file');

const consoleTransportsPorts = new Console({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    utilities.format.nestLike(),
  ),
});

const warnTransportsPorts = new DailyRotateFile({
  level: 'warn',
  dirname: 'logs',
  filename: 'warn-%DATE%.log',
  datePattern: 'YYYY-MM-DD-HH',
  zippedArchive: true,
  maxSize: '20m',
  maxFiles: '14d',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.simple(),
  ),
});

const infoTransportsPorts = new DailyRotateFile({
  level: 'info',
  dirname: 'logs',
  filename: 'info-%DATE%.log',
  datePattern: 'YYYY-MM-DD-HH',
  zippedArchive: true,
  maxSize: '20m',
  maxFiles: '14d',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.simple(),
  ),
});

@Module({
  imports: [
    WinstonModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        const logSwitch: DailyRotateFile[] = configService.get('log').onOff
          ? [warnTransportsPorts, infoTransportsPorts]
          : [];
        return {
          transports: [consoleTransportsPorts, ...logSwitch],
        } as WinstonModuleOptions;
      },
    }),
  ],
})
export class LogsModule {}
